package com.jp.knowledge.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.InfoDataDetailActivity;
import com.jp.knowledge.adapter.CollectionCommtemAdapter;
import com.jp.knowledge.adapter.OnItemListerner;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.HeadLineData;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.ProductUIModel;
import com.jp.knowledge.refresh.JpRefreshView;
import com.jp.knowledge.util.ResultSubscriber;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class CollectionNewsFragment extends Fragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, ResultSubscriber.OnResultListener, CollectionCommtemAdapter.DeleteIconClickListener {

	protected static final int GET_DATA_CODE = 0x01;
	protected static final int DELETE_ITEM_CODE = 0x02;

	protected Context mContext;
	protected View contentView;
	private LinearLayout remindView;
	protected CanRefreshLayout refreshLayout;
	protected RecyclerView contentRv;
	protected JpRefreshView footerView;

	protected int label;
	protected int page;
	protected List datas;
	protected List uncollectionData;
	protected RecyclerView.Adapter adapter;
	protected RecyclerView.LayoutManager layoutManager;

	private String cachePath;
	private FileCacheManager cacheManager;
	private LocalBroadCast localBroadCast;
	private LocalBroadcastManager localBroadcastManager;

	public Fragment newInstance(int label){
		this.label = label;
		return this;
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if (contentView == null) {
			mContext = getContext();
			contentView = View.inflate(mContext, R.layout.fragment_collection, null);
			remindView = (LinearLayout) contentView.findViewById(R.id.permissionView);
			refreshLayout = (CanRefreshLayout) contentView.findViewById(R.id.refresh);
			contentRv = (RecyclerView) contentView.findViewById(R.id.can_content_view);
			footerView = (JpRefreshView) contentView.findViewById(R.id.can_refresh_footer);
			remindView.findViewById(R.id.remind_btn).setVisibility(View.GONE);
			((ImageView)remindView.findViewById(R.id.remind_img)).setImageResource(R.mipmap.collection_tips);
			((TextView)remindView.findViewById(R.id.remind_text)).setText("暂无数据~");
			refreshLayout.setOnRefreshListener(this);
			refreshLayout.setOnLoadMoreListener(this);
			initData();
			initView();
			readCache();
		}
		return contentView;
	}

	@Override
	public void onResume() {
		for(int i = 0; i < uncollectionData.size(); i++)
			datas.remove(uncollectionData.get(i));
		adapter.notifyDataSetChanged();
		updateEmptyView();
		uncollectionData.clear();
		super.onResume();
	}

	@Override
	public void onDestroy() {
		localBroadcastManager.unregisterReceiver(localBroadCast);
		saveCache(cachePath, datas);
		super.onDestroy();
	}

	private void initData(){
		cachePath = getContext().getCacheDir().getPath()
				+ "/collection_data_"
				+ HttpHelper.uuid + "_"
				+ label
				+ ".data";
		cacheManager = new FileCacheManager();
		initBroadCast();
		uncollectionData = new ArrayList<>();
		datas = new ArrayList<>();
		adapter = initAdapter(datas);
		layoutManager = initLinearLayoutManager();
	}

	private void initBroadCast(){
		localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
			@Override
			public void done(Context context, Intent intent) {
				onBroadCastReceive(intent.getAction(), intent);
			}
		});
		localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(LocalBroadCast.COMM_CHANGE_SIZE);//改变字体大小
		intentFilter.addAction(LocalBroadCast.DETAIL_SC_BROAD);//收藏
		intentFilter.addAction(LocalBroadCast.LOGIN_SUCCESS_BROD);
		intentFilter.addAction(LocalBroadCast.LOGOUT_SUCCESS_BROD);
		intentFilter.addAction(LocalBroadCast.GET_LOGIN_INFO);
		localBroadcastManager.registerReceiver(localBroadCast,intentFilter);
	}

	protected void initView(){
		contentRv.setHasFixedSize(true);
		contentRv.setLayoutManager(layoutManager);
		contentRv.setAdapter(adapter);
	}

	protected RecyclerView.Adapter initAdapter(List datas){
		CollectionCommtemAdapter adapter = new CollectionCommtemAdapter(mContext, datas);
		adapter.setDeleteIconClickListener(this);
		adapter.setOnItemListener(new OnItemListerner() {
			@Override
			public void onItemClick(View view, int position) {
				CollectionNewsFragment.this.onItemClick(position);
			}
		});
		return adapter;
	}

	protected RecyclerView.LayoutManager initLinearLayoutManager(){
		return new LinearLayoutManager(mContext);
	}

	protected void onItemClick(int position){
		Intent intent = new Intent(mContext, InfoDataDetailActivity.class);
		HeadLineData data = (HeadLineData) datas.get(position);
		intent.putExtra("id", data.getId());
		intent.putExtra("type", data.getType());
		intent.putExtra("linkTitle", data.getTitle());
		try {
			intent.putExtra("linkIcon", data.getImglist().get(0).getSrc());
		}catch (Exception e){} finally {
			startActivity(intent);
		}
	}

	@Override
	public void onRefresh() {
		page = 1;
		getData(page);
	}

	@Override
	public void onLoadMore() {
		if (footerView.isLoadComplete())
			onCompleted(GET_DATA_CODE);
		else
			getData(++page);
	}

	private void getData(int page){
		JsonObject param = new JsonObject();
		param.addProperty("label", label);
		param.addProperty("page", page);
		HttpHelper.getInstance(mContext).getCollection(param, GET_DATA_CODE, this);
	}

	@Override
	public void onDelectIconClick(int position) {
		HeadLineData data = (HeadLineData) datas.get(position);
		onItemDelete(data.getId(), data.getType(), position*10+DELETE_ITEM_CODE);
	}

	protected void onItemDelete(String id, int type, int resultType){
		JsonObject param = new JsonObject();
		param.addProperty("id", id);
		param.addProperty("type", type);
		HttpHelper.getInstance(mContext).unCollection(param, resultType, this);
	}

	protected void itemDelete(int position){
		datas.remove(position);
		adapter.notifyItemRemoved(position);
		updateEmptyView();
	}

	@Override
	public void onStart(int requestType) {}

	@Override
	public void onCompleted(int requestType) {
		if(requestType == GET_DATA_CODE){
			if(page == 1)
				refreshLayout.refreshComplete();
			else
				refreshLayout.loadMoreComplete();
		}
	}

	@Override
	public void onError(int requestType) {
		onCompleted(requestType);
	}

	@Override
	public void onNext(IModel data, int requestType) {
		if(data.getErrcode() != 0){
			ToasUtil.toast(mContext, data.getMessage());
			onError(requestType);
		} else if(requestType == GET_DATA_CODE){
			updateRecyclerView(data, getDatasType());
		} else if(requestType%10 == DELETE_ITEM_CODE){
			itemDelete(requestType/10);
		}
	}

	protected Class getDatasType(){
		return HeadLineData.class;
	}

	private void updateRecyclerView(IModel model, Class classType){
		List tmpDatas = model.getList(classType);
		if(page == 1) {
			datas.clear();
			footerView.setLoadComplete(false);
		}
		if(tmpDatas != null && tmpDatas.size() > 0)
			datas.addAll(tmpDatas);
		else if(page > 1)
			footerView.setLoadComplete(true);
		contentRv.getAdapter().notifyDataSetChanged();
		updateEmptyView();
	}

	protected void updateEmptyView(){
		if(adapter.getItemCount() == 0)
			remindView.setVisibility(View.VISIBLE);
		else
			remindView.setVisibility(View.GONE);
	}

	private void readCache(){
		Observable.create(new Observable.OnSubscribe<List>() {
			@Override
			public void call(Subscriber<? super List> subscriber) {
				List datas = (List) cacheManager.readObject(cachePath);
				subscriber.onNext(datas);
				subscriber.onCompleted();
			}
		}).subscribeOn(Schedulers.io())
		.observeOn(AndroidSchedulers.mainThread())
		.subscribe(new Observer<List>() {
			@Override
			public void onCompleted() {
				refreshLayout.autoRefresh();
			}
			@Override
			public void onError(Throwable e) {
				onCompleted();
			}
			@Override
			public void onNext(List list) {
				if(list != null && list.size() > 0){
					datas.addAll(list);
					adapter.notifyDataSetChanged();
					updateEmptyView();
				}
			}
		});
	}

	private void saveCache(final String cachePath, final Object data){
		new Thread(new Runnable() {
			@Override
			public void run() {
				cacheManager.wirteObject(data, cachePath);
			}
		});
	}

	protected void onBroadCastReceive(String action, Intent intent){
		if(LocalBroadCast.COMM_CHANGE_SIZE.equals(action)) {
			((CollectionCommtemAdapter)adapter).changeTextSize();
		} else if(LocalBroadCast.DETAIL_SC_BROAD.equals(action)){
			for(Object data : datas){
				if(isSameItem(data, intent.getStringExtra("id"))){
					int isFollow = intent.getIntExtra("isCollection", 0);
					if(isFollow == 1)
						uncollectionData.remove(data);
					else
						uncollectionData.add(data);
					return;
				}
			}
		} else if(LocalBroadCast.LOGIN_SUCCESS_BROD.equals(action)
				|| LocalBroadCast.LOGOUT_SUCCESS_BROD.equals(action)
				|| LocalBroadCast.GET_LOGIN_INFO.equals(action)){
			datas.clear();
			adapter.notifyDataSetChanged();
			refreshLayout.autoRefresh();
		}
	}

	protected boolean isSameItem(Object data, String id){
		return (id != null && data != null && id.equals(((HeadLineData)data).getId()));
	}
}
